// pages/usercenter/member-list/index.js
const userModel = require('../../../model/user');
const {getMemberSubs, updateMemberToGuest} = require('../../../services/member/index');

Page({
  data: {
    members: [],
    filteredMembers: [],
    inviteCode: '',
    searchQuery: ''
  },
  onLoad(options) {
    const userId = options.userId || userModel.getUserData().info.id;

    if (!userId) {
      wx.showToast({
        title: '用户未登录',
        icon: 'error'
      });
      return;
    }

    const userData = userModel.getUserData();
    this.setData({
      inviteCode: userData.info.inviteCode,
    });

    getMemberSubs(userId)
      .then(res => {
        this.setData({ members: res.MEMBER, 
          filteredMembers: res.MEMBER // 复制用于搜索
         });
      })
      .catch(() => {
        wx.showToast({
          title: '加载失败',
          icon: 'error'
        });
      });
      
  },
  

  // 搜索输入
  onSearchInput(event) {
    const query = event.detail.value.toLowerCase();
    this.setData({ searchQuery: query });
    this.filterMembers();
  },

  // 过滤会员
  filterMembers() {
    const query = this.data.searchQuery;
    if (!query) {
      this.setData({ filteredMembers: this.data.members });
      return;
    }

    const filtered = this.data.members.filter(member =>
      (member.username && member.username.toLowerCase().includes(query)) ||
      (member.phone && member.phone.includes(query))
    );

    this.setData({ filteredMembers: filtered });
  },

  onInviteMember() {
    wx.showToast({
      title: '功能暂未开放',
      icon: 'none'
    });
  }
});
